import React, { useState, useMemo } from 'react'
import type { FC, ReactNode } from 'react'
import { memo } from 'react'
import { NavBar, SearchBar, Grid, Card, Empty } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import { useAppSelector } from '@/store'

import MySearch from './style'

interface Iprops {
  children?: ReactNode
}

const Search: FC<Iprops> = () => {
  const navigate = useNavigate()
  const back = () => navigate(-1)

  const {
    home: { hospitals }
  } = useAppSelector((state) => ({
    home: state.home
  }))

  const [keyword, setKeyword] = useState('')

  const [history, setHistory] = useState<string[]>([])

  const filteredHospitals = useMemo(() => {
    if (!keyword.trim()) return hospitals
    const lowerKeyword = keyword.toLowerCase()
    return hospitals.filter(
      (h: any) =>
        h.name.toLowerCase().includes(lowerKeyword) ||
        h.rank?.toLowerCase().includes(lowerKeyword) ||
        h.label?.toLowerCase().includes(lowerKeyword)
    )
  }, [keyword, hospitals])

  const onSearch = (val: string) => {
    setKeyword(val)
    if (val.trim() && !history.includes(val)) {
      setHistory((prev) => [val, ...prev.slice(0, 4)]) // 最多保存5条
    }
  }

  const handleHistoryClick = (word: string) => {
    setKeyword(word)
  }

  const handleItemId = (item: any) => {
    navigate(`/corder?id=${item.id}&hName=${item.name}`)
  }

  return (
    <MySearch>
      <NavBar onBack={back}>搜索医院</NavBar>

      {/* 搜索栏 */}
      <SearchBar
        value={keyword}
        placeholder="输入医院名、级别或标签"
        showCancelButton
        onSearch={onSearch}
        onChange={setKeyword}
        onClear={() => setKeyword('')}
      />

      {/* 搜索记录 */}
      {history.length > 0 && (
        <div className="search-history">
          <div className="memory">搜索记录</div>
          <Grid columns={3} gap={8}>
            {history.map((item, index) => (
              <Grid.Item key={index}>
                <div
                  className="grid-demo-item-block"
                  onClick={() => handleHistoryClick(item)}
                >
                  {item}
                </div>
              </Grid.Item>
            ))}
          </Grid>
        </div>
      )}

      {/* 医院列表 */}
      <div className="hospital-list">
        <div className="recommond">{keyword ? '搜索结果' : '推荐医院'}</div>

        {filteredHospitals.length > 0 ? (
          filteredHospitals.map((item: any) => (
            <Card key={item.id} className="hospital-card">
              <div className="hospital-item" onClick={() => handleItemId(item)}>
                <img
                  src={item.avatar_url}
                  alt={item.name}
                  className="hospital-img"
                />
                <div className="hospital-info">
                  <h4>{item.name}</h4>
                  <p className="level">
                    {item.rank}
                    {'\u00A0\u00A0'}
                    {item.label}
                  </p>
                  <p className="desc">{item.intro}</p>
                </div>
              </div>
            </Card>
          ))
        ) : (
          <Empty description="未找到相关医院" />
        )}
      </div>
    </MySearch>
  )
}

export default memo(Search)
